package com.sy.servlet;

import com.sy.utils.RandomUtils;

import javax.imageio.ImageIO;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

import static com.sy.constant.BusinessConstant.NOT_JSON;
import static com.sy.constant.BusinessConstant.SESSION_CODE;

@WebServlet("/validateCode")
public class ValidateCodeServlet extends AbstractBaseServlet {
    @Override
    protected Object doService(String action, HttpServletRequest req, HttpServletResponse res) throws Exception {
        Random r = new Random();
        //动态生成验证码图片
        //1.在内存中创建一个画板对象
        BufferedImage image = new BufferedImage(100, 40, BufferedImage.TYPE_INT_RGB);
        //2.获取画笔对象
        Graphics g = image.getGraphics();
        //3.为画笔设置颜色并填充矩形框
        g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
        g.fillRect(0, 0, 100, 40);
        //4.设置画笔颜色画字符串
        String code = RandomUtils.getRandomString(4);
        setSessionAttribute(req, SESSION_CODE, code);
        g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
        g.setFont(new Font("", Font.BOLD, 20));
        g.drawString(code, 30, 25);
        //5.画噪音线
        for (int i = 1; i <= 10; i++) {
            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
            g.drawLine(r.nextInt(100), r.nextInt(40), r.nextInt(100), r.nextInt(40));
        }
        //将内存中图片输出到响应流中
        res.setContentType("image/png");
        ImageIO.write(image, "png", res.getOutputStream());
        //表示当前处理结果返回的不是JSON，在BaseServlet中就不将返回结果包装成JSON数据了
        return NOT_JSON;
    }
}
